package com.sugou.web.pages.directives;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import freemarker.template.AdapterTemplateModel;
import freemarker.template.TemplateHashModelEx;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateModelIterator;
import freemarker.template.TemplateNumberModel;
import freemarker.template.TemplateScalarModel;
import freemarker.template.TemplateSequenceModel;

/**
 * freemarker指令工具
 * @author 童弘成
 *
 */
public class DirectiveUtils {
	public static Object getParamsValue(String name,Map<String, Object> params) throws TemplateModelException{
		Object value=params.get(name);
		return parseTemplate(value);
	}
	
	public static Object parseTemplate(Object value)throws TemplateModelException{
		if(value instanceof AdapterTemplateModel){
			return ((AdapterTemplateModel) value).getAdaptedObject(null);
		} else if(value instanceof TemplateNumberModel){
			return ((TemplateNumberModel)value).getAsNumber().longValue();
		}else if(value instanceof TemplateHashModelEx){
			TemplateHashModelEx hashex=(TemplateHashModelEx) value;
			TemplateModelIterator iterator=hashex.keys().iterator();
			Map<Object, Object> map=new LinkedHashMap<Object, Object>();
			while(iterator.hasNext()){
				TemplateScalarModel next=(TemplateScalarModel) iterator.next();
				String key=next.getAsString();
				map.put(key, parseTemplate(hashex.get(key)));
			}
			return map;
		}
		else if(value instanceof TemplateSequenceModel){
			TemplateSequenceModel sqnc=(TemplateSequenceModel) value;
			List<Object> list=new ArrayList<Object>();
			for (int i = 0; i < sqnc.size(); i++) {
				list.add(parseTemplate(sqnc.get(i)));
			}
			return list;
		}else  if(value instanceof TemplateScalarModel){
			return ((TemplateScalarModel)value).getAsString();
		}else{
			return value;
		}
	}
	
	public static Map<String, Object> unWrapperParams(Map<String, Object> params) throws TemplateModelException{
		Map<String, Object> paramsValues=new LinkedHashMap<String, Object>();
		Set<String> keys=params.keySet();
		for (String key : keys) {
			Object value=params.get(key);
			paramsValues.put(key, getParamsValue(key, params));
		}
		return paramsValues;
	}
}
